package zjc.bookkeeping.minepage.dDatamanagement;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;

import zjc.bookkeeping.R;
import zjc.bookkeeping.activity.MainActivity;
import zjc.bookkeeping.db.ConsumptionBean;
import zjc.bookkeeping.db.ConsumptionClassBean;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.db.UserBean;
import zjc.bookkeeping.model.Consumption;
import zjc.bookkeeping.server.Network;
import zjc.bookkeeping.service.ConsumptionService;
import zjc.bookkeeping.service.imp.ConsumptionServiceImp;
import zjc.bookkeeping.tools.GetFilePathFromUri;
import zjc.bookkeeping.tools.ReadCsv;
import zjc.bookkeeping.tools.TextDialog;
import zjc.bookkeeping.tools.ToolsClass;

public class DatamanagementMainActivity extends AppCompatActivity implements View.OnClickListener{
    ImageView backIv;
    TextView textView;
    LinearLayout importLl,exportLl,backupLl,downloadLl;
    List<ConsumptionBean> list = new ArrayList<>();
    List<ConsumptionBean> consumptionBeanList = new ArrayList<>();
    int outcome,income;
    String fileName;
    List<String> addBusiness = new ArrayList<>();
    ProgressDialog waitingDialog;
    ConsumptionService consumptionService = new ConsumptionServiceImp();
    List<Consumption> consumptionList = new ArrayList<>();
    UserBean userBean = new UserBean();
    boolean onlineFlag = false;

    TextView data_import_tv;
    TextView data_export_tv;
//    TextView data_file_cover_tv;
    TextView data_backup_tv;
    TextView data_download_tv;
    private int consumptionKey;
//    TextView data_cover_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datamanagement_main);
        userBean = DBManager.findUser();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                onlineFlag = Network.isOnline();
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        AutoSizeText();
        initView();
    }

    //字体大小适应
    private void AutoSizeText(){
        data_import_tv=findViewById(R.id.data_import_tv);
        data_export_tv=findViewById(R.id.data_export_tv);
//        data_file_cover_tv=findViewById(R.id.data_file_cover_tv);
        data_backup_tv=findViewById(R.id.data_backup_tv);
        data_download_tv=findViewById(R.id.data_download_tv);
//        data_cover_tv=findViewById(R.id.data_cover_tv);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            data_import_tv.setAutoSizeTextTypeUniformWithConfiguration(4,15,1, TypedValue.COMPLEX_UNIT_SP);
            data_export_tv.setAutoSizeTextTypeUniformWithConfiguration(4,15,1, TypedValue.COMPLEX_UNIT_SP);
//            data_file_cover_tv.setAutoSizeTextTypeUniformWithConfiguration(4,15,1, TypedValue.COMPLEX_UNIT_SP);
            data_backup_tv.setAutoSizeTextTypeUniformWithConfiguration(4,15,1, TypedValue.COMPLEX_UNIT_SP);
            data_download_tv.setAutoSizeTextTypeUniformWithConfiguration(4,15,1, TypedValue.COMPLEX_UNIT_SP);
//            data_cover_tv.setAutoSizeTextTypeUniformWithConfiguration(4,15,1, TypedValue.COMPLEX_UNIT_SP);
        }
    }

    private void initView() {
        textView = findViewById(R.id.tv1);

        backIv = findViewById(R.id.data_back_iv);

        importLl = findViewById(R.id.data_import_ll);
        exportLl = findViewById(R.id.data_export_ll);
        backupLl = findViewById(R.id.data_backup_ll);
        downloadLl = findViewById(R.id.data_download_ll);
//        coverLl = findViewById(R.id.data_cover_ll);
        waitingDialog = new ProgressDialog(DatamanagementMainActivity.this);
        waitingDialog.setMessage("数据处理中···");
        waitingDialog.setIndeterminate(true);
        waitingDialog.setCancelable(false);

        backIv.setOnClickListener(this);

        importLl.setOnClickListener(this);
        exportLl.setOnClickListener(this);
        backupLl.setOnClickListener(this);
        downloadLl.setOnClickListener(this);
//        coverLl.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.data_back_iv:
                finish();
                break;
            case R.id.data_import_ll:
                //动态申请储存权限
                ToolsClass.verifyStoragePermissions(this);
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                //设置类型，这里设置的是全部类型，没有过滤其他类型的文件
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
                break;
            case R.id.data_export_ll:
                //加载Dialog显示
                waitingDialog.show();
                //动态申请储存权限
                ToolsClass.verifyStoragePermissions(this);
                showExportDialog();
                break;
            case R.id.data_backup_ll:
                if (!onlineFlag){
                    ToolsClass.showToast(DatamanagementMainActivity.this,"网络不可用，请检查网络！", Toast.LENGTH_SHORT);
                    break;
                }
                if(userBean == null){
                    ToolsClass.showToast(DatamanagementMainActivity.this,"用户未登录，请登录后使用！", Toast.LENGTH_SHORT);
                    break;
                }
                waitingDialog.show();
                showBackUpDialog();
                break;
            case R.id.data_download_ll:
                if (!onlineFlag){
                    ToolsClass.showToast(DatamanagementMainActivity.this,"网络不可用，请检查网络！", Toast.LENGTH_SHORT);
                    break;
                }
                if(userBean == null){
                    ToolsClass.showToast(DatamanagementMainActivity.this,"用户未登录，请登录后使用！", Toast.LENGTH_SHORT);
                    break;
                }
                waitingDialog.show();
                showDownLoadDialog();
                break;
        }
    }

    //    接受到用户选择的文件路径
    @SuppressLint("NewApi")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("onActivityResult","启动，已经运行！");
        if (data != null){
            Uri uri = data.getData();
            Log.i("uri",uri +"");
            if (uri != null){
                String excelPath = GetFilePathFromUri.getFileAbsolutePath(this, uri);
                Log.i("excelPath",excelPath +"");
                int start = excelPath.lastIndexOf("/");
                fileName = excelPath.substring(start+1);
                if (excelPath.contains("alipay") && excelPath.contains(".csv")){
                    list = ReadCsv.readAlipayCsv(excelPath);
//                for (int i = 0;i<list.size();i++){
//                    addBusiness.add(list.get(i).getConsumption_business());
//                    consumptionClassBean = new ConsumptionClassBean();
//                    consumptionClassBean.setConsumption_class_id(0);
//                    consumptionClassBean.setConsumption_class_name(list.get(i).getConsumption_class_name());
//                    consumptionClassBean.setConsumption_class_kind(list.get(i).getConsumption_kind());
//                    consumptionClassBean.setConsumption_class_image("alipay_class");
//                    classBeans.add(consumptionClassBean);
//                    DBManager.insertConsumption(list.get(i));
//                Log.i("succeed "+ i +" 次","name: "+list.get(i).getConsumption_class_name()+"   remarks: "+list.get(i).getConsumption_remarks()
//                        +"   money: "+list.get(i).getConsumption_money()+"   business: "+list.get(i).getConsumption_business()+"   account: "+list.get(i).getaccount_id()
//                        +"   method: "+list.get(i).getConsumption_method()+"   time: "+list.get(i).getConsumption_time()+"   year: "+list.get(i).getConsumption_year()
//                        + "   month: "+list.get(i).getConsumption_month()+"   kind: "+list.get(i).getConsumption_day()+"数据更改成功！！！");
//                }
                }else if (excelPath.contains("微信") && excelPath.contains(".csv")){
                    list = ReadCsv.readWechatCsv(excelPath);
//                for (int i = 0;i<list.size();i++){
//                    addBusiness.add(list.get(i).getConsumption_business());
//                    consumptionClassBean = new ConsumptionClassBean();
//                    consumptionClassBean.setConsumption_class_id(0);
//                    consumptionClassBean.setConsumption_class_name(list.get(i).getConsumption_class_name());
//                    consumptionClassBean.setConsumption_class_kind(list.get(i).getConsumption_kind());
//                    consumptionClassBean.setConsumption_class_image("wechat_class");
//                    classBeans.add(consumptionClassBean);
//                    DBManager.insertConsumption(list.get(i));
//                Log.i("succeed "+ i +" 次","name: "+list.get(i).getConsumption_class_name()+"   remarks: "+list.get(i).getConsumption_remarks()
//                        +"   money: "+list.get(i).getConsumption_money()+"   business: "+list.get(i).getConsumption_business()+"   account: "+list.get(i).getaccount_id()
//                        +"   method: "+list.get(i).getConsumption_method()+"   time: "+list.get(i).getConsumption_time()+"   year: "+list.get(i).getConsumption_year()
//                        + "   month: "+list.get(i).getConsumption_month()+"   kind: "+list.get(i).getConsumption_day()+"数据更改成功！！！");
//                }
                }else if (excelPath.contains("青霄记账") && excelPath.contains(".csv")){
                    list = ReadCsv.importCSv(excelPath);
                } else {
                    ToolsClass.showToast(this,"选择的文件不对", Toast.LENGTH_SHORT);
                    return;
                }
        }
            //插入新增商家数据
            outcome = 0;
            income = 0;
            for (int i = 0; i < list.size(); i++){
                addBusiness.add(list.get(i).getConsumption_business());
                if (list.get(i).getConsumption_kind() == 0){
                    outcome++;
                }else {
                    income++;
                }
            }
            Set setBusiness = new HashSet();
            setBusiness.addAll(addBusiness);
            addBusiness.clear();
            addBusiness.addAll(setBusiness);
            //新增商家有的数据，但是数据库中没有
            List<String> nowBusiness = DBManager.getAllBusiness();
            Map<String,String> tempMap = new HashMap<>();
            for (String str:nowBusiness){
                tempMap.put(str,str);
            }
            List<String> newBusiness = new LinkedList<>();
            for (String str:addBusiness){
                if (!tempMap.containsKey(str)){
                    newBusiness.add(str);
                }
            }
            addBusiness.clear();
            addBusiness.addAll(newBusiness);
            waitingDialog.show();
            showImportDialog();
        }
    }
    //文件导入Dialog提示
    private void showImportDialog() {
        TextDialog textDialog = new TextDialog(this);
        textDialog.show();
        textDialog.setCancelable(false);
        int sum = outcome + income;
        String consumptionStr = "新增"+sum+"笔交易（"+outcome+"笔支出，"+income+"笔收入";
        String businessStr = "新增"+addBusiness.size()+"个商家";
        textDialog.setTextView(fileName,consumptionStr,businessStr);
        textDialog.setOnTextSureListener(new TextDialog.OnTextSureListener() {
            @Override
            public void onSureListener() {
                Log.i("waitingDialog","被使用");
                Log.i("数据","插入");
                for (int i = 0; i < list.size(); i++){
                    DBManager.insertConsumption(list.get(i));
                }
                for (int i = 0; i < addBusiness.size(); i++){
                    DBManager.createBusiness(addBusiness.get(i));
                }
                waitingDialog.dismiss();
            }
        });
        textDialog.setOnTextCancelListener(new TextDialog.OnTextCancelListener() {
            @Override
            public void onCancelListener() {
                waitingDialog.dismiss();
            }
        });
    }
    //数据导出Dialog提示
    private void showExportDialog() {
        TextDialog textDialog = new TextDialog(this);
        textDialog.show();
        textDialog.setCancelable(false);
        textDialog.setTextView("导出本账本的账单记录？","","");
        textDialog.setOnTextSureListener(new TextDialog.OnTextSureListener() {
            @Override
            public void onSureListener() {
                //获取系统的日期
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH)+1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                int second = calendar.get(Calendar.SECOND);
                //设置文件储存地址
                String path = Environment.getExternalStorageDirectory().getPath();
                Log.i("path",path);
                String filePath = path + "/Download/青霄记账_"+DBManager.getAccountName(DBManager.selectAccountId())+"_"+year+month+day+hour+minute+second+".csv";
                Log.i("filePath",filePath);
                //导出csv文件
                ReadCsv.exportCsv(filePath);
                waitingDialog.dismiss();
                ToolsClass.showToast(DatamanagementMainActivity.this,"文件位置："+filePath,Toast.LENGTH_SHORT);
            }
        });
        textDialog.setOnTextCancelListener(new TextDialog.OnTextCancelListener() {
            @Override
            public void onCancelListener() {
                waitingDialog.dismiss();
            }
        });
    }
    private void showBackUpDialog() {
        TextDialog textDialog = new TextDialog(this);
        textDialog.show();
        textDialog.setCancelable(false);
        consumptionBeanList = DBManager.findConsumptionByKey();
        textDialog.setTextView("是否将记录上传至服务器？","一共有"+consumptionBeanList.size()+"条记录还未上传","");
        textDialog.setOnTextSureListener(new TextDialog.OnTextSureListener() {
            @Override
            public void onSureListener() {
                for (int i = 0; i <consumptionBeanList.size(); i++){
                    Consumption consumption = new Consumption();
                    consumption.setConsumptionId(0);
                    consumption.setConsumptionClassName(consumptionBeanList.get(i).getConsumption_class_name());
                    consumption.setConsumptionRemarks(consumptionBeanList.get(i).getConsumption_remarks());
                    consumption.setConsumptionMoney((double) consumptionBeanList.get(i).getConsumption_money());
                    consumption.setConsumptionBusiness(consumptionBeanList.get(i).getConsumption_business());
                    consumption.setAccountUid(DBManager.getAccountUid(consumptionBeanList.get(i).getaccount_id()));
                    consumption.setConsumptionMethod(consumptionBeanList.get(i).getConsumption_method());
                    consumption.setConsumptionTime(consumptionBeanList.get(i).getConsumption_time());
                    consumption.setConsumptionKind(consumptionBeanList.get(i).getConsumption_kind());
                    consumptionList.add(consumption);
                }
                for (int i = 0; i <consumptionList.size(); i++){
                    Gson gson = new Gson();
                    String json = gson.toJson(consumptionList.get(i));
                    consumptionService.addConsumption(json,userBean.getUser_id(),consumptionBeanList.get(i));
                }
                waitingDialog.dismiss();
            }
        });
        textDialog.setOnTextCancelListener(new TextDialog.OnTextCancelListener() {
            @Override
            public void onCancelListener() {
                waitingDialog.dismiss();
            }
        });
    }
    private void showDownLoadDialog() {
        TextDialog textDialog = new TextDialog(this);
        textDialog.show();
        textDialog.setCancelable(false);
        consumptionBeanList = DBManager.findConsumptionByKey();
        textDialog.setTextView("是否将服务器数据缓存到本地？","","");
        textDialog.setOnTextSureListener(new TextDialog.OnTextSureListener() {
            @Override
            public void onSureListener() {
                DBManager.clearConsumption();
                consumptionService.findAllConsumption(userBean.getUser_id());
//                new Handler().postDelayed(new Runnable(){
//                    public void run() {
//
//                    }
//                }, 2000);
                waitingDialog.dismiss();
                ToolsClass.showToast(DatamanagementMainActivity.this,"数据缓存完成",Toast.LENGTH_SHORT);
            }
        });
        textDialog.setOnTextCancelListener(new TextDialog.OnTextCancelListener() {
            @Override
            public void onCancelListener() {
                waitingDialog.dismiss();
            }
        });
    }
}